import { ref } from 'vue'

export default function useMiddleInteractive() {
  const currentShow = ref('cd')
  const middleLStyle = ref(null)
  const middleRStyle = ref(null)
  const touch = {}
  let currentView = 'cd'
  function onMiddleTouchStart(e) {
    touch.startX = e.touches[0].pageX
    touch.startY = e.touches[0].pageY
    // 定义方向锁，防止滑动的时候向y轴偏移
    touch.directionLocked = ''
  }
  function onMiddleTouchMove(e) {
    // 获取偏移量
    const deltaX = e.touches[0].pageX - touch.startX
    const deltaY = e.touches[0].pageY - touch.startY

    const absDeltaX = Math.abs(deltaX)
    const absDeltaY = Math.abs(deltaY)

    if (!touch.directionLocked) {
      // h代表横向偏移，v代表纵向偏移, 一般来说你想滑动的时候x一定是比y要大的
      touch.directionLocked = absDeltaX >= absDeltaY ? 'h' : 'v'
    }
    // 如果是纵向偏移则什么都不要做
    if (touch.directionLocked === 'v') {
      return
    }

    // 如果为cd光盘则left=0，否则在歌词部分left=屏幕宽度
    const left = currentView === 'cd' ? 0 : -window.innerWidth
    // 限制偏移量范围, 保证在[-window.innerWidth, 0]之间, 因为手指滑动的时候会出现超出范围的现象
    const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX))
    // 设置百分比
    touch.percent = Math.abs(offsetWidth / window.innerWidth)
    if (currentView === 'cd') {
      // 从光盘移动到歌词距离大于0.2时(右滑)
      if (touch.percent > 0.2) {
        currentShow.value = 'lyric'
      } else {
        currentShow.value = 'cd'
      }
    } else {
      // 当歌词滑动到光盘距离大于0.8时(左滑)
      if (touch.percent < 0.8) {
        currentShow.value = 'cd'
      } else {
        currentShow.value = 'lyric'
      }
    }
    middleLStyle.value = {
      opacity: 1 - touch.percent,
      // transitionDuration 要么不设置，要么设置为0ms, 切记不能设置为其他，不然会有问题
      transitionDuration: '0ms'
    }
    middleRStyle.value = {
      transform: `translate3d(${offsetWidth}px, 0, 0)`,
      transitionDuration: '0ms'
    }
  }
  function onMiddleTouchEnd() {
    let offsetWidth
    let opacity
    if (currentShow.value === 'cd') {
      currentView = 'cd'
      offsetWidth = 0
      opacity = 1
    } else {
      currentView = 'lyric'
      offsetWidth = -window.innerWidth
      opacity = 0
    }
    const duration = 300
    middleLStyle.value = {
      opacity,
      transitionDuration: duration + 'ms'
    }
    middleRStyle.value = {
      transform: `translate3d(${offsetWidth}px, 0, 0)`,
      transitionDuration: duration + 'ms'
    }
  }
  return {
    currentShow,
    middleLStyle,
    middleRStyle,
    onMiddleTouchStart,
    onMiddleTouchMove,
    onMiddleTouchEnd
  }
}
